package network;

import model.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
//import java.net.Thread;
import java.io.IOException;
import java.util.List;
import java.util.LinkedList;

public class AcolyteGameServer extends Thread
{
  protected AcolyteGame myGame;
  protected boolean listening = true;
  protected int port = 4444;
  protected List<AcolyteServerThread> threads;
  
  public AcolyteGameServer()
  {
    threads = new LinkedList<AcolyteServerThread>();
    port = 4444;
    listening = true;
  }
  
  public AcolyteGameServer(int listeningPort)
  {
    threads = new LinkedList<AcolyteServerThread>();
    port = listeningPort;
    listening = true;
  }
  
  public void run()
  {
    ServerSocket serverSocket = null;
    //Socket clientSocket;
    try {
      serverSocket = new ServerSocket(port);
    } catch (IOException e) {
      System.out.println("Could not listen on port: " + port);
      System.exit(-1);
    }
    
    try
    {
      while(listening)
      {
        AcolyteServerThread temp = new AcolyteServerThread(this, serverSocket.accept());
        threads.add(temp);
        temp.start();
      }
      serverSocket.close();
    } catch (IOException e)
    {
      System.out.println("connection issue");
    }
  }
  
  public void broadcast(List<String> message)
  {
    for(AcolyteServerThread at: threads)
    {
      at.broadcast(message);
    }
  }
  
  public void removeThread(AcolyteServerThread ast)
  {
    threads.remove(ast);
    Runtime r = Runtime.getRuntime();
    r.gc();
    //r.freeMemory() returns how much memory is free, use for testing later
  }
  
  public static void main(String[] args)
  {
    AcolyteGameServer gs = new AcolyteGameServer();
    gs.run();
  }
}